﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ndns.Packet.Abstractions
{
    public struct DnsHostName : IEnumerable<string>, IEquatable<DnsHostName>
    {
        private static PunycodeEncoding Punycode => PunycodeEncoding.Default;

        private readonly string[] _domainParts;
        private int _hashCode;


        #region 构造DnsHostName实例

        public DnsHostName(IEnumerable<string> domainParts)
        {
            if (domainParts == null)
                throw new ArgumentNullException(nameof(domainParts));

            _domainParts = domainParts.ToArray();
            if (domainParts.Any(p => string.IsNullOrWhiteSpace(p) || p.Contains(".") || p.Contains("。")))
                throw new FormatException(nameof(domainParts));

            unchecked
            {
                int total = 17;
                foreach (var part in _domainParts)
                {
                    total = total * 37 + part.ToLowerInvariant().GetHashCode();

                }
                _hashCode = _domainParts.Length == 0 ? 0 : total;
            }
        }

        /// <summary>
        /// 利用给定的域名构造一个DnsHostName实例。
        /// </summary>
        /// <param name="hostName">给定的域名。</param>
        public DnsHostName(string hostName)
        {
            if (hostName == null)
                throw new ArgumentNullException(nameof(hostName));

            var domainParts = new List<string>();
            hostName = hostName.Replace('。', '.');
            if (hostName.EndsWith(".")) hostName = hostName.Substring(0, hostName.Length - 1);
            foreach (string eachPart in hostName.Split('.'))
            {
                domainParts.Add(DecodeDomainPart(eachPart));
            }
            _domainParts = domainParts.ToArray();

            unchecked
            {
                int total = 17;
                foreach (var part in _domainParts)
                {
                    total = total * 37 + part.ToLowerInvariant().GetHashCode();

                }
                _hashCode = _domainParts.Length == 0 ? 0 : total;
            }
        }

        public static explicit operator DnsHostName(string hostName)
        {
            return new DnsHostName(hostName);
        }
        public static explicit operator string(DnsHostName hostName)
        {
            return hostName.ToString();
        }

        private static string DecodeDomainPart(string s)
        {
            if (s.Length > 4 && 0 == string.Compare(s.Substring(0, 4), "xn--"))
                return Punycode.GetString(Encoding.ASCII.GetBytes(s.Substring(4)));
            else
                return s;
        }

        #endregion

        #region 获取相关信息

        public IReadOnlyList<string> DomainParts => _domainParts ?? Array.Empty<string>();

        /// <summary>
        /// 返回此实例表示的域名Punycode解码后的文字。（最后包括一个点）
        /// </summary>
        public override string ToString()
        {
            return string.Join(".", DomainParts) + ".";
        }

        #endregion

        #region Equals,HashCode实现


        public bool Equals(DnsHostName other)
        {
            if (_domainParts == null || _domainParts.Length == 0)
                return (other._domainParts == null || other._domainParts.Length == 0);

            if (other._domainParts == null)
                return false;

            if (ReferenceEquals(_domainParts, other._domainParts))
                return true;

            if (_domainParts.Length != other._domainParts.Length)
                return false;

            for (int i = 0; i < _domainParts.Length; i++)
            {
                if (!_domainParts[i].Equals(other._domainParts[i]))
                    return false;
            }

            return true;
        }

        public override bool Equals(object obj)
        {
            if (obj is DnsHostName)
                return Equals((DnsHostName)obj);
            return false;
        }

        public static bool operator ==(DnsHostName a, DnsHostName b) => a.Equals(b);
        public static bool operator !=(DnsHostName a, DnsHostName b) => !a.Equals(b);

        public override int GetHashCode()
        {
            return _hashCode;
        }

        #endregion
        
        #region IEnumerable<string>实现

        public IEnumerator<string> GetEnumerator()
        {
            return (IEnumerator<string>)DomainParts.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return DomainParts.GetEnumerator();
        }

        #endregion



    }
}
